import axios from 'axios'

const instance = axios.create()

instance.interceptors.request.use(function (config) {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.authorization = 'Bearer ' + token;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  if (response.headers.authorization) {
    localStorage.setItem('token', response.headers.authorization)
  }
  if (response.data.code != 0) {
    alert(response.data.msg)
  }
  return response;
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default instance;